package com.adb.ww2.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import com.adb.ww2.Log;
import com.adb.ww2.R;
import com.adb.ww2.fragment.DetailViewFragment;
import com.adb.ww2.fragment.ListViewFragment.OnHeadlineSelectedListener;

public class ListAndDetailsFragment extends FragmentActivity implements OnHeadlineSelectedListener{
	
	public static final String TAG = ListAndDetailsFragment.class.getCanonicalName();
	
	boolean mDualPane;
	int mCurCheckPosition = 0;

	/** 
	 * Fragment Activity that listen list fragment 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listanddetails_fragment);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	
	 /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
	void showDetails(int index) 
	{	
		
		 View detailsFrame = (View)findViewById(R.id.details);
		 
		 //Return true if in Landscape mode 
		 mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
		 
		
		if (mDualPane) {
        	
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.

			// Check what fragment is currently shown, replace if needed.
            DetailViewFragment details = (DetailViewFragment)getSupportFragmentManager().findFragmentById(R.id.details);
            
            if (details == null || details.getShowIndex() != index) {
                // Make new fragment to show this selection.
                details = DetailViewFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(ListAndDetailsFragment.this, DetailsFragmentActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }

	@Override
	public void onArticleSelected(int position) {
		Log.debug(TAG,"[ LISTEN CALLBACK ] " + position);
		showDetails(position);
	}
	
	
}
